#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash bwa-0.7.17.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
sudo yum install -y wget tar environment-modules libatomic readline-devel libXt-devel \
    bzip2-devel xz-devel libcurl-devel glibc-headers gcc-c++ pcre* 
  source /etc/profile

  echo "# R正在下载"
  wget -t 0 -T 20 -c -P $buildpath https://cran.r-project.org/src/base/R-4/R-4.2.1.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# R已经下载成功\033[0m"
  else
    echo -e "\033[31m# R下载失败,请重新执行脚本\033[0m"
    exit 1
  fi

  echo "# R 正在安装"
  tar -xzf $buildpath/R-4.2.1.tar.gz -C $buildpath && rm -rf $buildpath/R-4.2.1.tar.gz
  cd $buildpath/R-4.2.1
  FC=flang CC=clang CXX=clang++ ./configure --enable-R-shlib=yes --with-tcltk --prefix=$installpath/R-4.2.1
  make -j"$(nproc)" && make install
  echo -e "\033[1;32;1m# R 已经安装完毕\033[0m"

  cat >"$installpath/R-4.2.1/R-4.2.1_modulefiles" <<EOF
#%Module1.0
conflict R
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set R \$pwd
setenv R \$R
prepend-path PATH \$R/bin
prepend-path LIBRARY_PATH \$R/lib
prepend-path LD_LIBRARY_PATH \$R/lib
EOF

  rm -rf $buildpath/R-4.2.1

